package com.itheima.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmpleeMapper;
import com.itheima.reggie.service.EmpleeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;


@Service



public class EmpleeServiceImpl extends ServiceImpl<EmpleeMapper, Employee> implements EmpleeService {


    @Override
    public Page<Employee> page( Integer page, Integer pageSize, String name) {

        Page<Employee> pageInfo = new Page(page, pageSize);

        //必须指明实体类
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();

        AbstractWrapper wrapper = queryWrapper.like(StringUtils.isNotBlank(name),
                Employee::getName,
                name);

        this.page(pageInfo, wrapper);
        return pageInfo;
    }

    @Override
    public R<Employee> login(Employee employee, HttpServletRequest request) {

        //获取输入的用户名
        String username = employee.getUsername();

        //根据用户名查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Employee::getUsername, username);
        Employee oldEmployee = this.getOne(queryWrapper);

        //判断用户是否存在
        if (oldEmployee == null) {
            return R.error("用户名不存在");
        }

        //比较密码是否相同,首先对用户输入密码进行加密与数据库密码字段比较
        String inputPassword = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        String selectPassword = oldEmployee.getPassword();
        /*if (!inputPassword.equals(selectPassword)) {
            return R.error("密码不正确");
        }*/
        if (!StringUtils.equals(inputPassword, selectPassword)) {
            return R.error("密码不正确");
        }


        //查看用户是否被禁用
        Integer status = oldEmployee.getStatus();
        if (status == 0) {
            return R.error("用户被禁用");
        }

        //把员工信息放在session里
        request.getSession().setAttribute("employee", oldEmployee.getId());

        return R.success(oldEmployee);
    }
}
